package logic

import (
	"api/model/order_food_category"
	"api/model/order_food_goods"
	"api/service"
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderFoodCategoryDelLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderFoodCategoryDelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderFoodCategoryDelLogic {
	return &OrderFoodCategoryDelLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderFoodCategoryDelLogic) OrderFoodCategoryDel(req *types.RequestOrderFoodCategoryDel) (resp *types.ResponseMsg, err error) {
	conn := sqlx.NewMysql(l.svcCtx.Config.DataSource)
	categoryModel := order_food_category.NewOrderFoodCategoryModel(conn)

	busService := service.NewBusinessService(l.ctx, l.svcCtx)
	bus := busService.GetLoginBusinessInfo()

	err = categoryModel.Delete(l.ctx, req.Id, bus.Id)

	if err != nil {
		return service.ReturnError()
	}

	// 删除分类下的所有商品
	redis := l.svcCtx.RedisPool.Get()
	defer redis.Close()

	goodsModel := order_food_goods.NewOrderFoodGoodsModel(conn)
	goodsModel.DeleteByCategoryId(l.ctx, req.Id)

	goodsService := service.NewOrderFoodService(l.ctx, l.svcCtx)
	goodsService.DelGoodsList(redis, bus.Id, req.Id)

	return service.ReturnOk()
}
